import pymysql

class connect_my_database:
    def __init__(self, host='localhost', port=3306, user='root', password='root', database='finance'):
        self.host = host
        self.port = port
        self.user = user
        self.password = password
        self.database = database
        self.connection = None
        self.cursor = None

    def connect(self):
        try:
            self.connection = pymysql.connect(
                host=self.host,
                port=self.port,
                user=self.user,
                password=self.password,
                database=self.database
            )
            self.cursor = self.connection.cursor()
        except Exception as e:
            print(f"连接错误：{e}")
            self.cursor.close()

    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.connection:
            self.connection.close()

    def execute(self, sql, params=None):
        try:
            if not self.connection or not self.cursor:
                self.connect()

            self.cursor.execute(sql, params)
            self.connection.commit()

        except Exception as e:
            print(f"执行失败，错误信息如下：{e}")

    def update(self, sql, params=None):
        self.execute(sql, params)

    def select(self, sql, params=None):
        self.execute(sql, params)
        try:
            return self.cursor.fetchall()
        except Exception as e:
            print(f"查询异常，报错如下:{e}")



